package puzzle.projecteuler;

import java.math.BigInteger;

import org.apache.commons.lang.StringUtils;


public class ContinuedFraction {

	private Integer[] pre;
	private Integer[] repeated;
	
	public ContinuedFraction(Integer[] pre, Integer[] repeated) {
		this.pre = pre;
		this.repeated = repeated;
	}
	
	public String toString() {
		
		return "[" + StringUtils.join(this.pre, ",") + ";(" + StringUtils.join(this.repeated, ",") + ")]";
	}

	public Integer[] getPre() {
		return pre;
	}

	public void setPre(Integer[] pre) {
		this.pre = pre;
	}

	public Integer[] getRepeated() {
		return repeated;
	}

	public void setRepeated(Integer[] repeated) {
		this.repeated = repeated;
	}
	
	private int get(int i) {
		if (i < this.pre.length) {
			return this.pre[i];
		} else {
			i -= this.pre.length;
			if (this.repeated.length == 0) {
				throw new RuntimeException("Wrong Action!");
			} else {
				return this.repeated[i%this.repeated.length];
			}
		}
	}
	
	public Fraction fractionValue(int n) {
		
		int m = n-1;
		BigInteger p = BigInteger.valueOf(get(m));
		BigInteger q = BigInteger.ONE;
		for (int i = m-1; i > -1; i --) {
			BigInteger x = p;
			p = BigInteger.valueOf(get(i)).multiply(p).add(q);
			q = x;
		}
		return new Fraction(p,q);
	}
}
